const App = getApp();
// /api/getTimeBuyList
import Api, { GET_CUR_TIME_BUY, GET_TIME_BUY_LIST, GET_TIME_BUY_GOODS_LIST, ADD_CART, ADD_SUBSCRIBE} from '../../utils/api';
import { handPic,getUrl } from '../../utils/util';
Page({

    data: {
        left:'',
        nodeId:'',
        
        active_list: [],
        active_list_ctime:[],                                               // 活动列表时间戳  

        start_time: '',     // 1 活动开始的时间戳         
        act_time: '',       // 2 选中场次的开始时间戳  只要1 2相等就显示倒计时 

        timestamp: {},      // 当前时间戳 ==> 用于倒计时  
        cur_time:'',        // 当前时间

        show:true           //倒计时结束时影藏
    },

    formSubmit:function(e){
        let {id} = e.currentTarget.dataset,
            { formId } = e.detail,
            _this = this;
        const {key} = this.data;
        
 
        Api.fetch(
            ADD_SUBSCRIBE,
            {
                key:key,
                tb_goods_id:id,
                formid:formId
            },
            resp => {
                wx.showToast({
                    title: '设置成功',
                })
            }
        )
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let _this = this,
            key;

        //判断是否登录
        if (Api.checkLogin(function () {
            _this.onLoad(options);
            _this.onShow();
        })) {
            key = Api.getKey();
            _this.setData({
                key: key
            })
        }
    },

    navigateTo: function (e) {
        const tip = e.target.dataset.tip;
        let url;
        url = '../goods_details/goods_details';
        if(tip=='pay'){
            url = '../payment/payment';
        };
        App.navigateTo(url)
    },

    /** 切换节点 设置scroll-left距离 */
    switch_schedule: function (e) {
        let num, { active_list } = this.data;
        const { index, idx } = e.currentTarget.dataset;

        /** 设置active 状态 */
        active_list.map((items) => {
            items.map((item) => { item.active = false})
        });
        active_list[index][idx].active = true;
        // 活动ID 
        const id = active_list[index][idx].id;
       
       /** 切换请求数据更换抢购列表*/
       wx.showLoading({ title: '加载中' }) ;
       this.setData({list: []});

        Api.fetch(GET_TIME_BUY_GOODS_LIST, { tbid: id }, goods_list => {
            wx.hideLoading();

            goods_list.map((v, k) => {
                v.default_img = handPic(v.default_img, 4);
                v.width = (v.buy_num / v.tb_num * 100).toFixed();
            })

            this.setData({
                list: goods_list
            });

        });

        this.setData({ 
            active_list: active_list, 
            act_time: active_list[index][idx].ctime
        });

        /** 设置scroll-left距离 */
        switch (index) {
            case 0:
                num = idx;
                break;
            case 1:
                num = active_list[0].length + idx;
                break;
            case 2:
                num = active_list[0].length + active_list[1].length + idx;
                break;
        };
        this.getNode(index,num);
    },

    /** 获取节点 */
    getNode: function (_index,num){
        const that = this;
        let spaceWidth, titleWidth, nodeWidth, scroll_left;
        /** 日期title的宽度 */
        wx.createSelectorQuery().select('.schedule-items .title').boundingClientRect(function (rect) {
            titleWidth = (_index + 1) * rect.width;
        }).exec();

        /** 抢购节点的宽度 */
        wx.createSelectorQuery().select('.schedule-items_node').boundingClientRect(function (rect) {
            nodeWidth = num*rect.width;
            scroll_left = titleWidth + nodeWidth;
            that.setData({ left: scroll_left});
        }).exec();

    },

    //  时间戳转换
    timestamp: function (_d) {
        //  得到当前的时间
        let y, m, d, h, minute, s;
        y = _d.getFullYear();
        m = _d.getMonth() + 1;
        d = _d.getDate();

        h = _d.getHours();
        s = _d.getSeconds();
        minute = _d.getMinutes();

        return ({ y, m, d, h, minute, s })
    },

    /** 请求活动列表数据 */
    timebuy: function (e) {
        let { id } = e.currentTarget.dataset;
        const { key } = this.data;

        Api.fetch(ADD_CART, { key: key, goods_id: id, goods_num: 1, type: 'timebuy' }, resp => {
            let url = getUrl("pay", { ctype: 'timebuy' });
            wx.navigateTo({
                url: url
            })
        })
    },

    /**  生命周期函数--监听页面显示 */
    onShow: function () {
        let _this = this;

        /**  请求活动时间表 */
        Api.fetch(GET_TIME_BUY_LIST, {}, resp => {
            let num , _index;
            /** 获取 active=true 的索引  如果全部为false num=undefined 将会报错*/
            resp.map((items,index)=>{
                items.map((item,idx)=>{
                    if (item.active){
                        this.setData({ start_time: item.ctime});
                     
                        switch (index){
                            case 0:
                                _index=0;
                                num = idx;
                                break;
                            case 1:
                                _index = 1;
                                num = resp[0].length + idx;
                                break;
                            case 2:
                                _index = 2;
                                num = resp[0].length + resp[1].length + idx;
                                break;
                        }
                    }
                });
            });
            /** 快抢中 已开抢 即将开抢 */
            _this.setData({
                active_list:resp
            },_=>{
                this.getNode(_index,num);
            });
        });

        /**  获取当前时间戳 */
        Api.fetch(GET_CUR_TIME_BUY,{}, resp =>{
         
            if(resp){
                /** 倒计时 */
                this.countDown(resp.ctime, resp.curtime)
                _this.setData({
                    info: resp,
                    act_time: resp.ctime,
                    start_time:resp.ctime
                }, function () {
                    
                    const { info } = _this.data;
                    /**  获取活动列表 */
                    Api.fetch(GET_TIME_BUY_GOODS_LIST, { tbid: info.tbid }, goods_list => {
                        goods_list.map((v, k) => {
                            v.default_img = handPic(v.default_img, 4);
                            v.width = (v.buy_num / v.tb_num * 100).toFixed();
                        })

                        _this.setData({
                            list: goods_list
                        });
                    })
                })
            }
           
        })
    },
    /** 倒计时 */
    countDown: function (ctime, curtime){
        const that=this;
        let endTime = ctime+3600;
        let _curtime = curtime;

        let remainTime =  endTime - curtime;
        let {h,m,s} = App.countDown(remainTime);
        this.setData({ cur_time: curtime, timestamp: { h, m, s } });

        this.timer = setInterval(_=>{
            remainTime-=1;
            let { h, m, s } = App.countDown(remainTime);
            _curtime+=1;

            this.setData({
                cur_time: _curtime,
                timestamp: { h, m, s }
            });
            //  倒计时结束清除 倒计时 状态改为已开抢
            if (remainTime==0){
                this.setData({show:false})
                clearInterval(this.timer);
            }
        },1000);

       
    },
    /**  生命周期函数--监听页面初次渲染完成 */
    onReady: function () { },

    /** 生命周期函数--监听页面隐藏 */
    onHide: function () {
    
    },

    /** 生命周期函数--监听页面卸载 */
    onUnload: function () {
    
    },

    /** 页面相关事件处理函数--监听用户下拉动作  */
    onPullDownRefresh: function () {
    
    },

    /**  页面上拉触底事件的处理函数 */
    onReachBottom: function () {
    
    },
    /**  页面卸载 清除定时器 */
    onUnload: function () {
        clearInterval(this.timer)
    },
    /**  用户点击右上角分享 */
    onShareAppMessage: function () {
    
    }
})